package com.siyoumi.app.sys.wx.thread;

import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;

@Slf4j
@Component
public class WxCenterThread {
    private ThreadPoolTaskExecutor pool = null;

    public ThreadPoolTaskExecutor getPool() {
        if (pool != null) {
            return pool;
        }

        pool = new ThreadPoolTaskExecutor();
        // 核心线程数,线程池创建时候初始化的线程数
        pool.setCorePoolSize(10);
        // 最大线程数,线程池最大的线程数，只有在缓冲队列满了之后才会申请超过核心线程数的线程
        pool.setMaxPoolSize(10);
        // 缓冲队列,用来缓冲执行任务的队列
        pool.setQueueCapacity(0);
        // 允许线程的空闲时间,当超过了核心线程之外的线程在空闲时间到达之后会被销毁
        pool.setKeepAliveSeconds(60);
        // 线程池名的前缀
        pool.setThreadNamePrefix("WxCenter-Thread-");
        // 缓冲队列满了之后的拒绝策略,由调用线程处理（一般是主线程）
        pool.setRejectedExecutionHandler(new WxCenterPolicy());
        pool.initialize();
        log.debug("threadPools init");
        return pool;
    }

    private class WxCenterPolicy
            implements RejectedExecutionHandler {
        /**
         * Creates a {@code DiscardPolicy}.
         */
        public WxCenterPolicy() {
        }

        /**
         * 线程池，爆满处理
         *
         * @param r
         * @param e
         */
        public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
            //发送队列，异步处理
            log.info("rejectedExecution");

            String url = WxCenterThreadLocal.getUrl();
            String xml = WxCenterThreadLocal.getXml();

            log.info("url: {}", url);
            log.info("xml: {}", xml);
        }
    }
}
